var mongoose = require('mongoose');
const Products = require('../models/product.model');

// 新增
exports.create = function(req, res, next) {
    const products = new Products(req.body);
    products.save().then((data) => {
        res.json(data);
    });
}

// 修改
exports.update = function(req, res, next) {
    const id = req.params.id;
    Products.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
        // 这里返回的数据是修改之前的数据，不是修改之后的数据
    })
}

// 删除
exports.remove = function(req, res, next) {
    const id = req.params.id;
    Products.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    })
}

// 查询
exports.list = function(req, res, next) {
    var page           = req.body.page ? req.body.page : 1,
        rows           = req.body.rows ? req.body.rows : 5,
        queryCondition = {};                                 // 查询条件

    if (req.body.drugName && req.body.drugName.trim().length > 0) {
        drugName       = req.body.drugName;
        queryCondition = {
            "drugName": new RegExp(drugName, 'i')
        }
    }

    Products.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })

}

// 查找单条数据
exports.getData = function(req, res, next) {
    var id = req.params.id;
    Products.findById(id).then(data => {
        res.json(data);
    })
}

// 批量删除
exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',');
    if (ids.length > 0) {
        Products.remove({ _id: { $in: ids } }).then(data => {
            res.json({
                'message': 'delete ok',
                status   : 200
            })
        })
    }
}